//
//  ApplyHealthViewController.swift
//  LongTermInsurance
//
//  Created by zolobdz on 2018/11/28.
//  Copyright © 2018年 HeChao. All rights reserved.
//

import UIKit
import SnapKit
import ObjectMapper

class ApplyHealthViewController: UIViewController {

    lazy var saveButton: UIButton = {
        let button = UIButton()
        button.setTitle("保  存", for: .normal)
        button.backgroundColor = CDColor.themePink
        return button
    }()
    
    lazy var questionView: QuestionView = {
        let view = QuestionView()
        return view
    }()
    
    lazy var dataSource: [QuestionModel] = {
        
        let path = CDArchiverPath.healthStateFilePath
        if FileManager.default.fileExists(atPath: path) {
            
            if let dict = NSDictionary(contentsOfFile: path) {
                if let array = dict["health"] as? [[String: Any]]{
                    let array = Mapper<QuestionModel>().mapArray(JSONArray: array)
                    return array
                }
            }
        }
        
        let plistPath = Bundle.main.url(forResource: "apply_health", withExtension: "plist")!
        let dataDict = NSArray(contentsOf: plistPath) as! [[String: Any]]
        let array = Mapper<QuestionModel>().mapArray(JSONArray: dataDict)
        return array
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "就医及健康状况"
        view.backgroundColor = CDColor.grayBackgroundColorA
        view.addSubview(questionView)
        view.addSubview(saveButton)
        
        questionView.snp.remakeConstraints { (make) in
            make.top.right.left.equalTo(0)
            make.bottom.equalTo(saveButton.snp.top).offset(-20)
        }
        
        saveButton.snp.remakeConstraints { (make) in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(-(view.safeAreaInsets.bottom + 50))
            } else {
                make.bottom.equalTo(-50)
                // Fallback on earlier versions
            }
            make.height.equalTo(30.0)
        }
        
        saveButton.addTarget(self, action: #selector(saveButtonAction), for: UIControlEvents.touchUpInside)
        
        
        questionView.dataSource = dataSource
        questionView.tableView.reloadData()
    }
    
    @objc func saveButtonAction() {
        
        for model in dataSource {
            if !model.items.isEmpty {
                if model.selectedIndex.count == 0 || (model.selectedIndex.count == 1 && model.selectedIndex.first! == IndexNone) {
                    makeToast("请填写-\(model.questionTitle)")
                    return
                }
            }
        }
        
        let path = CDArchiverPath.healthStateFilePath
        let json = dataSource.toJSON()
        
        let dict = NSMutableDictionary()
        dict.setValue(json, forKey: "health")
        let success = dict.write(toFile: path, atomically: false)
    
        if success {
            makeToast("保存成功")
            navigationController?.popViewController(animated: true)
        } else {
            makeToast("保存失败")
        }
    }
    
}
